package cn.edu.wynu.apis.jdbc;

import java.sql.*;

public class MyFirstJDBC {
    // 数据库连接信息
    private static final String URL = "jdbc:mysql://localhost:3306/jdbc_learn?useSSL=false&serverTimezone=UTC";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    public static void main(String[] args) {
        testConnection();
        queryAllStudents();
    }

    public static void testConnection() {
        Connection connection = null;
        try {
            // 1. 加载驱动（MySQL 8.x自动注册，此步可省略）
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. 建立连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            // 3. 检查连接是否成功
            if (connection != null) {
                System.out.println("✅ 数据库连接成功！");

                // 获取数据库元数据
                DatabaseMetaData metaData = connection.getMetaData();
                System.out.println("数据库名称: " + metaData.getDatabaseProductName());
                System.out.println("数据库版本: " + metaData.getDatabaseProductVersion());
            }

        } catch (ClassNotFoundException e) {
            System.out.println("❌ 找不到驱动类: " + e.getMessage());
        } catch (SQLException e) {
            System.out.println("❌ 数据库连接失败: " + e.getMessage());
        } finally {
            // 4. 关闭连接
            if (connection != null) {
                try {
                    connection.close();
                    System.out.println("🔒 数据库连接已关闭");
                } catch (SQLException e) {
                    System.out.println("关闭连接时出错: " + e.getMessage());
                }
            }
        }
    }

    public static void queryAllStudents() {
        System.out.println("\n📋 示例1：查询所有学生");

        String sql = "SELECT id, name, age, grade, created_time FROM students";

        try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {

            System.out.println("ID\t姓名\t年龄\t专业\t创建时间");
            System.out.println("-".repeat(50));

            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                int age = rs.getInt("age");
                String grade = rs.getString("grade");
                Timestamp createdTime = rs.getTimestamp("created_time");
                System.out.printf("%d\t%s\t%d\t%s\t%s\n",
                        id, name, age, grade, createdTime);
            }

        } catch (SQLException e) {
            System.out.println("查询失败: " + e.getMessage());
        }
    }
}
